
package com.hanhai.zrb.mobile.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hanhai.common.cache.Cache;
import com.hanhai.common.util.CommonUtil;
import com.hanhai.zrb.mobile.util.FrontLoginUtil;

/**
 * spring mvc 登陆拦截器
 *
 */
public class FrontApiLoginInterceptor extends HandlerInterceptorAdapter {

	@Resource
	private Cache loginCache;

	private String loginUrl;
	
	@Value("#{configProperties['zhaorongbao.domain']}")
	private String default_domain;

	public static final Logger logger = LoggerFactory
			.getLogger(FrontApiLoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		FrontLoginUtil.setCurrentUser(null);
		// User项目也需要响应图片
		boolean b = handler instanceof HandlerMethod;
		if (!b) {
			return true;
		}
		FrontLoginUtil.initCurrentApiUser(request, loginCache);

		boolean exist = CommonUtil.hasLoginNeedless(handler);
		if (exist) {
			return true;
		}
		
		// 需要登录的
		if (FrontLoginUtil.getCurrentUser() != null) {
			int status = FrontLoginUtil.checkLoginStatus(FrontLoginUtil.getCurrentUser());
			if(status==2){
				FrontLoginUtil.removeCurrentApiUser(request, response, loginCache, default_domain);
				CommonUtil.jsonMobileOtherLogin(response);
				return false;
			}
			return true;
		} else {
			// 需要登录，但是没有登录
			// 异步
			/*if (CommonUtil.isAjaxRequest(request)) {
				response.setHeader(BLOGIN, "true");
				CommonUtil.jsonLogin(response);
			}
			// 同步
			else {
				response.sendRedirect(loginUrl);
			}*/
			
			CommonUtil.jsonMobileLogin(response);
			return false;
		}

		//return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		FrontLoginUtil.setCurrentUser(null);
		super.afterCompletion(request, response, handler, ex);
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginCenterUrl) {
		this.loginUrl = loginCenterUrl;
	}

}
